/* eslint-disable vue/no-v-model-argument */
<template>
    <div class="site-list">
        <!-- 搜索 -->
        <list-filter
            @search="search"
            :stage-refSubject="stageRefSubject"
            :pos-list="posList"
         ></list-filter>
        
        <div class="operate-btn">
            <el-button type="primary" @click="addModel('add')">新增账号</el-button>
            <el-dropdown>
                <el-button type="primary" :disabled="!userList.length">
                    批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                    <el-dropdown-item @click="roleModel(true)">批量添加角色</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
        <!-- 表格 -->
        <div class="table-container">
            
            <!-- 列表 -->
            <table-wrap v-if="tableData.length"
                hideHeader
                :total="total"
                :loading="loading"
                v-model:pageSize="filterForm.pageSize"
                v-model:pageIndex="filterForm.pageIndex"
                @request-list="getList"
                :table-data="tableData"
                :noSelection="false"
            >
                <el-table
                    ref="multipleTable"
                    :data="tableData"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column :selectable="setTableCanSelect" type="selection" width="55"/>
                    <el-table-column label="序号" show-overflow-tooltip fixed="left">
                        <template #default="scope">
                            <div>{{(filterForm.pageIndex - 1 )*filterForm.pageSize+scope.$index+1}}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" align="center" label="姓名" min-width="130" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="userName" align="center" label="账号" min-width="130" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="phone" align="center" label="手机号" min-width="130" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="eduId" align="center" label="教育ID" min-width="130" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="stageSubjectGrades" align="center" label="学段/学科" min-width="130" show-overflow-tooltip>
                        <template #default="scope">
                            <span>{{fmtStageName(scope.row.stageSubjectGrades)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="positionTypeName" align="center" label="职位类型" min-width="130" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="school" align="center" label="所在单位" min-width="130" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="roleList" label="角色" align="center" min-width="130" show-overflow-tooltip>
                        <template #default="scope">
                            <span>{{fmtRoles(scope.row.roleList)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="创建时间" min-width="130" show-overflow-tooltip>
                        <template #default="scope">
                            <span>{{formatTime(scope.row.gmtCreate)}}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="state" label="状态" align="center" min-width="130" show-overflow-tooltip>
                        <template #default="scope">
                            <div>
                                <el-switch
                                    v-model="scope.row.state"
                                    width="50px"
                                    class="ml-2"
                                    inline-prompt
                                    active-text="启用"
                                    inactive-text="禁用"
                                    :active-value="1"
                                    :inactive-value="0"
                                    @change="changeState(scope.row)"
                                />
                            </div>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="操作" width="220" fixed="right">
                        <template #default="scope">
                            <el-button link type="primary" @click="addModel('edit',scope.row)">编辑</el-button>
                            <el-button link type="primary" @click="resetPas(scope.row)">重置密码</el-button>
                            <el-button link type="primary" @click="roleModel(false, scope.row)">分配角色</el-button>
                            <el-button link type="primary" @click="delUser(scope.row)">删除</el-button>
                            <!-- <el-button link type="primary" @click="viewInfo(scope.row)">查看详情</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
                
            </table-wrap>
            <no-data v-else></no-data>
        </div>
        <!-- 创建用户dialog -->
        <edit-model
            ref="editModelRef"
            :form-data="editForm"
            :isEdit="isEdit"
            :pos-list="posList"
            @submit="submitForm"
        ></edit-model>
        <!-- 用户详情dialog -->
        <view-detail
            ref="infoRef"
            :user-info="editForm"
        ></view-detail>
        <!-- 分配角色dialog -->
        <role-model
            v-if="roleLayer.show"
            :dialogParams="roleLayer"
            :institutionId="route.query.id"
            :account="currentUser"
            @dialog:close="closeRolesDialog"
            @dialog:confirm="confirmRolesDialog"
            :user-list="userList"
            :isMultiple="isMultiple"
            type="2"
        >
        </role-model>
    </div>
</template>

<script >
import { defineComponent, toRefs, ref, reactive, toRef, computed, onMounted, nextTick } from 'vue'
import tableWrap from '@/components/table-wrap/table-wrap.vue'
import noData from '@/components/no-data.vue'
import listFilter from './part/user-filter.vue'
import editModel from './part/edit-model.vue'
import viewDetail from './part/user-view-model.vue'
import roleModel from '@/views/wand-user/dialog/assign-roles.vue'
import { ArrowDown } from '@element-plus/icons-vue'
import Fn from '@/lib/fn.js'
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import { formatTimestamp, fmtStageName } from '@/lib/tools'
import { useStageList } from '@/hooks/useStageList'
import { useStageRefSubjectList } from '@/hooks/useStageRefSubject'
import { useMessage } from '@/hooks/useMessage'


import {
    schoolPositionList,
    institutionPositionList
} from '../filter-data'
export default defineComponent({
    name: 'UserList',
    components: {
        tableWrap,
        noData,
        listFilter,
        editModel,
        viewDetail,
        roleModel,
        ArrowDown
    },
setup(props) {
    const store = useStore()
    const editModelRef = ref(null) // 编辑弹窗ref
    const infoRef = ref(null) // 用户信息弹窗ref
    const route = useRoute()

    const {messageSuccess, messageError} = useMessage();

    // 学科学段数据
    useStageRefSubjectList((data) => (state.stageRefSubject = data.map(item => ({...item, code: item.stage, name: item.stageName}))))
    // 状态数据
    const state = reactive({
        isMultiple: false, // 是否批量分配
        roleLayer: {
            show: false,
            title: '分配角色'
        },
        currentUser: {},
        // 列表搜索数据
        filterForm: {
            pageIndex: 1,
            pageSize: 10
        },
        editForm: {},
        stageRefSubject: [], // 学段学科年级列表
        loading: false,
        tableData: [], // 用户列表
        total: 0,
        isEdit: 'add',
        userList: [], // 选择的用户
        posList: [] // 职位类型
    })
    // 方法集合
    const fns = {
        // 初始数据
        init(){
            fns.getList()
            fns.getPositionType()
        },
        setTableCanSelect(row){
          return row.state == 1
        },
        // 获取职位类型列表
        getPositionType(){
            store.dispatch('proxyAction', {
                name: 'getPositionType',
                message: false,
                queries: {
                    institutionType: route.query.institutionType
                }
            }).then((res) => {
                state.posList = res.data || []
            }).catch(err => {
                messageError(err.message || '操作失败')
            })
        },
        // 多选用户
        handleSelectionChange(val){
            console.log(val)
            state.userList = val.map(item => item.memberId)
        },
        // 关闭添加账号对话框
        closeRolesDialog() {
            state.roleLayer.show = false
            state.currentUser = null
        },
        // 账号对话框confirm
        confirmRolesDialog() {
            state.roleLayer.show = false
            fns.getList()
        },
        // 保存用户
        submitForm(data){
            const api = state.isEdit == 'add' ? 'memberSave' : 'memberUpdate'
            store.dispatch('proxyAction', {
                name: api,
                data: {
                    ...data,
                    institutionId: route.query.id
                }
            }).then((res) => {
                messageSuccess('成功')
                editModelRef.value.close()
                fns.getList()
            }).catch(err => {
                console.log(err)
            })

        },
        // 查看用户详情弹窗
        viewInfo(row){
            state.editForm = row
            infoRef.value.open()
        },
        // 切换用户状态
        changeState(data){
            let main = data.state == 1 ? '确定启用' : '确定禁用'
            let sub = data.state == 1 
            ? '启用后，该用户可以正常访问平台，是否确认启用？'
            : '禁用后，该用户将无法进入平台，是否确认禁用？'
            const func = Fn.Confirm(function() {
                store.dispatch('proxyAction', {
                    name: 'frontEnableUser',
                    data: {
                        yn: data.state,
                        userId: data.sysUserId
                    }
                }).then((res) => {
                    messageSuccess('成功')
                    fns.getList()
                }).catch(err => {
                    messageError(err.message || '操作失败')
                })
            }, sub, main, () => (data.state = data.state == 1 ? 0 : 1))
            func()
        },
        // 分配角色弹窗
        roleModel(type = false, row = {}){
          if(row.state == 0){
            return messageError('该用户已禁用，暂不能分配角色')
          }
            state.isMultiple = type
            state.currentUser = row
            state.roleLayer.show = true
        },
        // 重置密码
        resetPas: Fn.Confirm(function(row){
            store.dispatch('proxyAction', {
                name: 'resetUserPwd',
                message: false,
                data: {
                    clientId: 'sanren-wand-pc',
                    userId: row.memberId
                }
            }).then(() => {
                messageSuccess('密码重置成功')
            }).catch(err => {
                messageError(err.message || '操作失败')
            })

        }, '密码将被重置为srt123，是否确认？', '重置密码'),
        // 删除用户
        delUser: Fn.Confirm(function(row){
            store.dispatch('proxyAction', {
                name: 'quietInstitution',
                message: false,
                queries: {
                    memberId: row.memberId,
                    institutionId: route.query.id
                }
            }).then(() => {
                messageSuccess('删除成功')
                fns.getList()
            }).catch(err => {
                messageError(err.message || '操作失败')
            })

        }, '确认要删除这个账号吗？', '确认删除'),
        // 列表搜索
        search (data){
            state.filterForm = data
            fns.getList()
        },
        // 格式化时间戳
        formatTime(time){
            return formatTimestamp(time, 'YYYY-MM-DD HH:mm:ss')
        },
        // 列表角色格式化展示
        fmtRoles(role = []){
            return role.map(item => item.roleName).join(' ')
        },
        // 弹窗添加/修改
        async addModel(type = 'add', row = {}){
            state.isEdit = type
            if(type == 'edit'){
                state.editForm = row
            }
            await nextTick()
            editModelRef.value.open()
        },
        // 获取列表
        getList () {
            state.loading = true;
            store.dispatch('proxyAction', {
                name: 'instutionMemberList',
                message: false,
                data: {
                    ...state.filterForm,
                    institutionId: route.query.id || '',
                    memberId: '',
                    stageArr: undefined,
                    time: undefined,
                    dtTenant: route.query.dtTenant || ''
                }
            }).then((res) => {
                state.tableData = res.data.rows || [];
                state.total = res.data.total;
            }).catch(err => {
                messageError(err.message || '操作失败')
            }).finally(() => {
                state.loading = false;
            })
        }
    }
    // 计算属性
    const comp = {
        // 组织类型
        isInstitution: computed(() => route.query.institutionType),
        // 职位类型
        jobTypeList: computed(() => {
            return route.query.institutionType == 1 ? schoolPositionList : institutionPositionList
        })
    }
    onMounted(() => {
        fns.init()
    })
    return{
        ...toRefs(state),
        ...fns,
        ...comp,
        editModelRef,
        infoRef,
        route,
        fmtStageName
    }
}
})

</script>

<style lang="scss" rel="stylesheet/scss" scoped>
    .table-container{
        .btns{
            margin-bottom: 10px;
        }
    }
    .tag-item{
        margin-right: 10px;
    }
 
</style>
